package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetMealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;


@Service
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishMapper dishMapper;
    @Override
    public void saveSetMeal(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        //1.先插入套餐表
        setmealMapper.saveSetMeal(setmeal);
        //2..添加多个菜
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
            /**
             *  插入基本套餐表信息来获取套餐的主键id（setmealId），
             *  因为新增多个菜的时候的setmeal的id为空的,在xml映射文件中返回新添加套餐的主键id,就需要两个属性，
             *  可以在Mapper映射文件中查看那两个属性
             */
            Long setmealId = setmeal.getId();
            setmealDishes.forEach(setmealDish -> {
                setmealDish.setSetmealId(setmealId);
            });
        setmealDishMapper.saveSetMealWithDish(setmealDishes);
    }

    @Override
    public PageResult pageSetmeal(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        //注意这里要用VO来接收，根据需求文档可知，需要套餐对应的分类名称
        Page<SetmealVO> page=setmealMapper.pageSetmeal(setmealPageQueryDTO);
        long total = page.getTotal();
        List<SetmealVO> result = page.getResult();
        if (total==0){
            throw new BaseException(MessageConstant.SETMEAL_NOTFOUND);
        }
        return new PageResult(total,result);
    }

    @Override
    public void deleteSetmealByIds(List<Long> ids) {
        /**
         * 注意:删除套餐表的同时,套餐与菜品的关系表也要删除
         * 起售中的套餐不能删除
         */
        //1.先根据id查询套餐表判断这些被删除的套餐是否为起售状态，否则抛异常
        List<Setmeal> setmealist=setmealMapper.selectByIds(ids);
        setmealist.forEach(setmeal -> {
            Integer status = setmeal.getStatus();
            if(status.equals(StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });
      if(setmealist!=null && setmealist.size()>0){
          //2.根据套餐的id集合来批量删除套餐
          setmealMapper.deleteSetmealByIds(ids);
          //3.根据套餐的id集合批量删除套餐菜品关系表
          setmealDishMapper.delSetmealDishByIds(ids);
      }
    }

    @Override
    public SetmealVO getById(Long id) {
        //1.根据套餐的id查套餐表和分类表,因为涉及分类名(categoryName)
        SetmealVO setmealVO=setmealMapper.getById(id);
        //2.根据套餐的id查询套餐菜品关系表,返回为SetmealDish对象
        List<SetmealDish> setmealDish=setmealDishMapper.getBySetmealId(id);
        //3.最后封装为VO对象
        setmealVO.setSetmealDishes(setmealDish);
        return setmealVO;
    }

    @Override
    public void UpDateSetmeal(SetmealDTO setmealDTO) {
//        1.先修改套餐表（Setmeal）的基本信息
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealMapper.UpdateSetmeal(setmeal);
//        2.根据setmealDTO的setmealDishes属性删除原来的套餐菜品关系数据(SetmealDish)
        setmealDishMapper.delSetmealDish(setmealDTO.getId());
//        3.插入新的套餐菜品关系数据
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        Long setmealId = setmeal.getId();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        setmealDishMapper.saveSetMealWithDish(setmealDishes);
    }

    @Override
    public void StatusSetmeal(Integer status, Long setMealId) {
        Setmeal setmeal = Setmeal.builder().status(status).id(setMealId).build();
//        先判断套餐内是否包括停售的菜品，否则不能起售
//        因为涉及两个表查询而且还包含相同字段，可以用连接查询
        List<Dish> Dishes=dishMapper.selectStatus(setMealId);
        //加上判空处理，避免编写sql语句出现问题返回空的值到集合里
        if(Dishes.size()>0 && Dishes!=null){
            Dishes.forEach(dish -> {
                if(dish.getStatus()==StatusConstant.DISABLE){
                    throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
            });
        }
        setmealMapper.UpdateSetmeal(setmeal);
    }

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }

}
